Soru & Cevap

Volley Kütüphanesi ile çoklu veri indirme ...

04.12.2019 - 03:50

Merhaba aslında sorunum basit ancak çözümü internnette bulumadığımı daha doğrusu ne diye araştırmalıyım emin olamadığım için sormak gereksinimi duyuyorum.

Soruma gelirsek internet üzerinden hali hazırda ayarladığım ses dosyalarını çoklu bir şekilde indirme yapmam gerekiyor ancak volley kullanırken asekron yapıda çalıştığı için for içinde sorun oluştuğunu fark ettim bende bir Thread.sleep(200) koyarak işi biraz yavaşlattım. Çalışmaya çalıştı ancak doğru olmadığını ve doğrusunu öğrenmek adına daha iyi nasıl yaparım sormak istedim.

İşte kodlarım:

package com.vaktinde.app.net;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

import java.util.HashMap;
import java.util.Map;

public class InputStreamVolleyRequest extends Request<byte[]> {
    private final Response.Listener<byte[]> mListener;
    private Map<String, String> mParams;

    //create a static map for directly accessing headers
    public Map<String, String> responseHeaders;

    public InputStreamVolleyRequest(int method, String mUrl, Response.Listener<byte[]> listener,
                                    Response.ErrorListener errorListener, HashMap<String, String> params) {
        // TODO Auto-generated constructor stub

        super(method, mUrl, errorListener);
        // this request would never use cache.
        setShouldCache(false);
        mListener = listener;
        mParams = params;
    }

    @Override
    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return mParams;
    }

    @Override
    protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
        //Initialise local responseHeaders map with response headers received
        responseHeaders = response.headers;

        //Pass the response data here
        return Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(byte[] response) {
        mListener.onResponse(response);
    }

}

Bu özelleştirilmiş Volley request classım

class GetDowlandFile2 extends AsyncTask<String, Integer, String> {

        private ProgressDialog progressDialog;
        private KuranSound kuranSound;
        private List<KuranAyet> kuranAyetList;
        private NotificationManager mNotifyManager;
        private NotificationCompat.Builder mBuilder;
        private String channelId = "DowlandFile";
        private InputStream input;
        private BufferedOutputStream output;

        public GetDowlandFile2(KuranSound kuranSound, List<KuranAyet> kuranAyetList) {
            this.kuranSound = kuranSound;
            this.kuranAyetList = kuranAyetList;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(view.getContext());
            progressDialog.setMax(kuranAyetList.size());
            progressDialog.setTitle(getSTR(R.string.app_name));
            progressDialog.setMessage(getSTR(R.string.progress_dialog2));
            progressDialog.setProgress(0);
            progressDialog.setCancelable(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.show();

            mNotifyManager = (NotificationManager) view.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
            mBuilder = new NotificationCompat.Builder(view.getContext(), channelId);
            mBuilder.setContentTitle(getSTR(R.string.app_name))
                    .setContentText(getSTR(R.string.progress_dialog2))
                    .setSmallIcon(R.drawable.ic_stat_vaktinde);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(channelId, "Dosya İndirme", NotificationManager.IMPORTANCE_LOW);
                mNotifyManager.createNotificationChannel(channel);
            }
        }

        @Override
        protected String doInBackground(String... f_url) {
            try {
                File f = new File(view.getContext().getExternalCacheDir(), "KuranSound/" + kuranSound.getLink());
                //Eğer dosya yoksa oluştur
                if (!f.exists()) {
                    f.mkdirs();
                }

                for (int i = 0; i < kuranAyetList.size(); i++) {

                    File soundFile = new File(view.getContext().getExternalCacheDir(),
                            "KuranSound/" + kuranSound.getLink() + "/" + kuranAyetList.get(i).getSureno() + "_" + kuranAyetList.get(i).getAyetno() + ".mp3");

                    if (!soundFile.exists()) {

                        final int finalI = i;
                        InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET,
                                view.getContext().getResources().getString(R.string.api_kuran) +
                                        kuranSound.getLink() + "/" + kuranAyetList.get(i).getSureno() + "_" + kuranAyetList.get(i).getAyetno() + ".mp3",
                                new Response.Listener<byte[]>() {
                                    @Override
                                    public void onResponse(byte[] response) {
                                        // TODO handle the response
                                        try {
                                            if (response != null) {

                                                int count;
                                                try {
                                                    input = new ByteArrayInputStream(response);
                                                    File sdCardDirectory = view.getContext().getExternalCacheDir();
                                                    File dowlandFile = new File(sdCardDirectory, "KuranSound/" +
                                                            kuranSound.getLink() + "/" +
                                                            kuranAyetList.get(finalI).getSureno() + "_" +
                                                            kuranAyetList.get(finalI).getAyetno() + ".mp3");

                                                    output = new BufferedOutputStream(new FileOutputStream(dowlandFile));
                                                    byte[] data = new byte[1024];

                                                    long total = 0;

                                                    while ((count = input.read(data)) != -1) {
                                                        total += count;
                                                        output.write(data, 0, count);
                                                    }


                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        } catch (Exception e) {
                                            // TODO Auto-generated catch block
                                            Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
                                            e.printStackTrace();
                                        }
                                    }
                                }, new Response.ErrorListener() {

                            @Override
                            public void onErrorResponse(VolleyError error) {
                                // TODO handle the error
                                error.printStackTrace();
                            }
                        }, null);
                        RequestQueue mRequestQueue = Volley.newRequestQueue(view.getContext(), new HurlStack());
                        request.setRetryPolicy(new DefaultRetryPolicy(50000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                        mRequestQueue.add(request);
                    }
                    //volley ile veri indirirken bir
                    // öncekinin işleminin bitmesi beklenmediği
                    // için burada bir bekleme ayarladım ancak çok sağlıklı değil.
                    Thread.sleep(200);
                    publishProgress(i + 1);
                    mBuilder.setProgress(kuranAyetList.size(), i + 1, false);
                    mNotifyManager.notify(10, mBuilder.build());

                }
                output.flush();
                output.close();
                input.close();


            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Integer currentProgress = values[0];
            progressDialog.setProgress(currentProgress);
        }

        @Override
        protected void onPostExecute(String file_url) {
            if (progressDialog != null) {
                progressDialog.dismiss();
                kuranPageFragment.setKuanAyetExists();
                mBuilder.setContentText("İndirme Tamamlandı.").setProgress(0, 0, false);
                mNotifyManager.notify(10, mBuilder.build());
                mNotifyManager.cancel(10);
                KuranSoundFragment.this.dismiss();

            }
        }
    }

Buda verileri indirmek için kullandığım AsyncTask classım.

Sorumu yinelemek gerekir ise Thread.sleep(200) olmaz ise yapı yanlış çalışıyor bası dosyaları indirmiyor. Sebebi az çok belli for içinde volley kütüphanesi asekron çalışıyor ancak bunun önene nasıl başka yoldan geçerim. Yardımlarınızı bekliyorum. Teşekkürler.

26 Görüntülenme

1 Cevap

Sitedeki sorulara cevap verebilmek için giriş yapın ya da üye olun.

Profile picture for user cbozkurt367
cbozkurt367
05.12.2019 - 03:04
Kardeşim kodlarında küçük bir hata var onu düzeltmen lazım
Recep Özen
05.12.2019 - 03:07
Hata mı söylerseniz çok sevinirim.